<?php
declare (strict_types=1);

namespace quick\admin\library\service;


use quick\admin\Service;

/**
 *
 * Class CaptchaService
 * @package quick\librarys
 */
class CaptchaService extends Service
{

    private $charset = 'ABCDEFGHKMNPRSTUVWXYZ23456789'; // 随机因子


    /**
     * 验证码服务初始化
     * @param array $config
     * @return static
     */
    public function initialize(array $config = []): CaptchaService
    {
        // 动态配置属性
        foreach ($config as $k => $v) if (isset($this->$k)) $this->$k = $v;
        // 返回当前对象
        return $this;
    }


    /**
     * @param string $id
     * @param int $length
     * @return string
     */
    public function create(string $id,int $length = 0)
    {
        $code = $this->generate($length);
        $this->app->cache->set(md5($id), $code, 360);
        return $code;
    }



    /**
     * 检查验证码是否正确
     * @param string $code 需要验证的值
     * @param null|string $uniqid 验证码编号
     * @return boolean
     */
    public function check(string $code, ?string $uniqid = null): bool
    {
        $_uni = is_string($uniqid) ? $uniqid : input('uniqid', '-');
        $key = md5($_uni);
        $_val = $this->app->cache->get($key, '');
        if (is_string($_val) && strtolower($_val) === strtolower($code)) {
            $this->app->cache->delete($key);
            return true;
        } else {
            return false;
        }
    }


    /**
     * @return string
     */
    private function generate(int $len = 4):string
    {
        [$code, $length] = ['', strlen($this->charset) - 1];
        for ($i = 0; $i < $len; $i++) {
            $code .= $this->charset[mt_rand(0, $length)];
        }
        return $code;
    }

}
